from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
# Create your views here.

from .TypesViews import GetAllTypes
from ..models import Types,Goods
from . IndexViews import upgoods
from django.core.urlresolvers import reverse
import os
import re


# 商品列表显示
def good_index(request):
    goods = Goods.objects.all().order_by('tid')

    # 搜索模块
    # 接受参数 types(搜索类别) keywords(搜索条件)
    types    = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None) 
    # 判断是否有搜索类别
    if types:
        if types == 'all': 
            pass
        # 商品标签搜索
        elif types == 'title' :
            goods = goods.filter(title__contains=keywords)            
        # 商品库存搜索
        elif types == 'num':            
            try:                                
                keywords = float(keywords)
                goods = goods.filter(num__gt=keywords)
            except Exception as e:
                goods = Goods.objects.all().order_by('tid')
        # 商品点击量搜索
        elif types == 'clicknum':
            try:                                
                keywords = int(keywords)
                goods = goods.filter(clicknum__gt=keywords)
            except Exception as e:
                goods = []
            
        # 所属分类搜索
        elif types == 'tid_name':
            if keywords:
                mi = []
                # goods = goods.tid.filter(name__contains=keywords).goods_set.all()
                for i in goods:            
                    st = i.tid.name
                    if keywords in st:
                        mi.append(i)
                if len(mi):
                    goods = mi
                else:
                    goods = []
            else:
                pass


        # 状态搜索
        elif types == 'status':
            if keywords:                
                if "热销".count(keywords):
                    keywords = 1
                elif "上架".count(keywords):
                    keywords = 0
                elif "下架".count(keywords):
                    keywords = 2
                else:
                    keywords = 5
                goods = goods.filter(status__contains=keywords)  
            else:
                pass

            
    # 数据分页 
    from django.core.paginator import Paginator
    # 实例化分页对象,参数1,数据列表  参数2 每页显示的条数
    p = Paginator(goods, 4)
    # 获取当前的页码数
    page = request.GET.get('biao',1)
    page = int(page)
    # 获取当前页的数据
    goods = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range
    
    info = {'data':goods}
    return render(request,'admin/goods/index.html',info)

# 商品添加 跳转
def good_add(request):

    data = {'info':GetAllTypes()}
    return render(request,'admin/goods/add.html',data)
# 商品添加 执行
def good_insert(request):
    # 获取页面传入的数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    # 绑定 商品类 与 商品  1对多关系
    tid = int(data['tid'])
    data['tid'] = Types.objects.get(id=tid)
     
    # 商品图片
    myfile = request.FILES.get('pic',None)
    if myfile:
        data['pic'] = upgoods(myfile)
    else:
        return HttpResponse('<script>alert("必须选择上传的商品图片");location.href="'+reverse('myadmin_good_add')+'"</script>')
        
    # 加入数据库
    Goods.objects.create(**data)    
    return HttpResponse('<script>location.href="'+reverse('myadmin_good_index')+'"</script>')
    
# 商品删除
def good_delete(request):
    try:
        # 获取要删除的商品id
        id = request.GET['id']
        ju = Goods.objects.get(id=id)
        # 将数据库中该数据的状态变成3
        ju.delete()
        data = {'jieguo':'删除成功','pan':1}
        return JsonResponse(data)    
    except Exception as e:
        data = {'jieguo':'删除失败','pan':0}
        return JsonResponse(data)    

# 商品信息修改
def good_setgood(request):
    uid = request.GET.get('uid')
    uid = int(uid)
    ju = Goods.objects.get(id = uid)
    data = {'info':GetAllTypes(),'ju':ju}
    return render(request,'admin/goods/set.html',data)

# 商品修改执行

def good_update(request):

    # 接受页面数据
    jie = request.POST.dict()
    jie.pop('csrfmiddlewaretoken')
    id = jie['id']

    # 获取数据库数据
    ku = Goods.objects.get(id=id)
    ku.num    =  jie['num']
    ku.title  =  jie['title']
    ku.price  =  jie['price']
    ku.status =  jie['status']

    
    if jie.get('info'):
        ku.info   =  jie['info']
    else:
        pass


    # 获取图片信息
    jie['pic'] = request.FILES.get('pic',None)
    # 判断图片有没有新图提交   有新图提交 jie['pic'] =None  有提交4b4a0bf39c9298e0f6484f9237220c11.jpg

    # 判断 是否更新图片 不更新 jie['pic'] =None
    if jie['pic']:
        # 删除之前的图片
        os.remove('./'+ku.pic)
        # 将新图片存入数据库
        ku.pic = upgoods(jie['pic'])
    else:
        pass
             
    # 更改类别
    tid = int(jie['tid'])
    jie['tid'] = Types.objects.get(id=tid)
    ku.tid    =  jie['tid']

    ku.save()
    return HttpResponse('<script>location.href="'+reverse('myadmin_good_index')+'"</script>')
    




